#! /usr/bin/env node 

const args=process.args.slice(2)

console.log(args);

let PORT =8000;
const http=require('http');
const path=require('path')
const {existsSync,statSync,readdirSync,readFileSync} =require('fs')
const {networkInterfaces} =require('os')
const {exec} =require('child_process')

function createserver()
{
    http.createServer((req,res)=>
    {
        let rootpath=process.cwd();
        rootpath=path.join(rootpath,req.url)
        if(existsSync(rootpath))
        {
            if(statSync(rootpath).isDirectory())
            {
                let html=readFileSync(path.join(__dirname,'../lists/index.js'),'utf-8')
                let dirarr=readdirSync(rootpath)
                let lihtml=dirarr.map(item=>{
                    return `<li>
                        <a href='${path.join(req.url,item)}'>${item}</a>    
                    </li>`
                }).join('')
                html=html.replace('{{list}}',lihtml)
                res.end(html)
            }
            else
            {
                res.end(readFileSync(rootpath),'utf-8')
            }
        }
        else
        {
            res.end('路径不存在')
        }
    }).listen(PORT,()=>{
        console.log("服务器启动");
        console.log(networkInterfaces().WLAN);
        const hostname = networkInterfaces().WLAN.find(item=>item.family == 'IPv4').address;
        console.log(hostname);
        const address=`http://${hostname}:${PORT}`;
        exec(`start ${address}`)
    })
}
if(args.length == 0)
{
    createserver();
}
else
{
    if(args[0] == '-v')
    {
        console.log('版本号');
    }
    else if(args[0] == '-p')
    {
        console.log('端口号'+args[1]);
        PORT = args[1];
        createserver()
    }
}
